package com.flyu.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class SessionDome1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 解决乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        // 获取Session
        HttpSession session = req.getSession();
        // 给Session中存东西
        session.setAttribute("name", "飞龙");
        // 获取session的id
        String id = session.getId();
        // 判断session是否新创建
        if (session.isNew()){
            resp.getWriter().write("Session创建成功:"+id);
        }else{
            resp.getWriter().write("Session已经在服务器中存在了："+id);
        }
        // 将sessionId添加到cookie中
        Cookie cookie = new Cookie("JSESSIONID", id);
        resp.addCookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
